package com.example.demo.controller;

import com.example.demo.domain.Girl;
import com.example.demo.domain.Result;
import com.example.demo.repository.GirlRepository;
import com.example.demo.service.GirlService;
import com.example.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by steve
 * 2018/7/10
 */
@RestController
public class GirlController {

    @Autowired
    private GirlRepository repository;

    @Autowired
    private GirlService service;

    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    /**
     * 查询所以女生
     * @return
     */
    @GetMapping("/girls")
    public List<Girl> getGirls(){
        logger.info("girl lists");
        return repository.findAll();
    }

    /**
     * 添加女生
     * @return
     */
    @PostMapping("/girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());
        return ResultUtil.success(repository.save(girl));
    }

    /**
     * 查询单个女生
     * @param id
     * @return
     */
    @GetMapping("/girls/{id}")
    public Girl girlOne(@PathVariable("id") Integer id){
        return repository.findById(id).get();
    }

    /**
     * 修改女生信息
     * @param id
     * @param age
     * @param cup
     * @return
     */
    @PutMapping("/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("age") Integer age, @RequestParam("cupSize") String cup){
        Girl girl = new Girl();
        girl.setCupSize(cup);
        girl.setAge(age);
        girl.setId(id);
        return repository.save(girl);
    }

    /**
     * 删除女生
     * @param id
     */
    @DeleteMapping("/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer id){
        repository.deleteById(id);
    }


    /**
     * 通过年龄来查找女生
     * @param age
     * @return
     */
    @GetMapping("/girls/age/{age}")
    public List<Girl> girlAge(@PathVariable("age") Integer age){
        return repository.findByAge(age);
    }

    @GetMapping("/girls/two")
    public void insertTwo(){
        service.insertTwo();
    }

    @GetMapping("/girls/getAge/{id}")
    public void getAge(@PathVariable Integer id) throws Exception{
        service.getAge(id);
    }

}
